﻿using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Linq;
using KPIS.GERP.ESS.APP.App_UI.Forms;
using KPIS.GERP.ESS.BLL;
using System.Collections.Generic;

namespace KPIS.GERP.ESS.APP
{
    public partial class Master : System.Web.UI.MasterPage
    {
        private B_MessageSend send = new B_MessageSend();
        private B_SECURITY_Users user = new B_SECURITY_Users();
        private B_HrmEmployees emp = new B_HrmEmployees();
        public static string strServerName { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            //cmdInbox.Attributes.Add("onClick", "return false;");
            lbNotification.Attributes.Add("onClick", "return false;");
            strServerName = Request.Url.Host + (ConfigurationSettings.AppSettings["SubSystem"].ToString().Length > 0
                ? "/" + ConfigurationSettings.AppSettings["SubSystem"].ToString()
                : "");

            if (!Page.IsPostBack)
            {
                //Page.DataBind();
            }

            string strControlName = ContentPlaceHolder1.Page.ToString();

            if (strControlName == "ASP.app_ui_forms_login_aspx")
            {
                RadMenu1.Visible = false;
                PanelDetail.Visible = false;
            }
            else if (strControlName == "ASP.app_ui_forms_selectsystem_aspx")
            {
                RadMenu1.Visible = false;
                PanelDetail.Visible = true;
                cmdSelectSystem.Visible = false;
                cmdLogout.Visible = true;
            }
            else
            {
                RadMenu1.Visible = true;
                PanelDetail.Visible = true;
                cmdSelectSystem.Visible = true;
                cmdLogout.Visible = false;
            }

            if (!IsPostBack)
            {
                PanelHeader.BackImageUrl = "~/App_UI/Images/PageViews/" +
                                           ConfigurationSettings.AppSettings["Header"].ToString();
                HttpCookie cookie = Request.Cookies["UserDetail"];
                if (cookie != null && Session["EmpSeq"] == null)
                {
                    int nEmpSeq = -1;
                    string strEmpSeq = cookie["EmpSeq"];

                    if (strEmpSeq != null)
                    {
                        if (strEmpSeq.Length > 0)
                        {
                            nEmpSeq = Convert.ToInt32(strEmpSeq);
                        }
                    }

                    if (nEmpSeq > -1)
                    {
                        Session["EmpSeq"] = Convert.ToString(nEmpSeq);
                        Session["UserName"] = emp.GetEmployeeFullName(nEmpSeq);
                        Session["UserSeq"] = cookie["UserSeq"];
                        Session["WorkingJobSiteSeq"] = cookie["WorkingJobSiteSeq"];
                        Session["Height"] = cookie["Height"];
                        Session["TokenKey"] = cookie["TokenKey"];
                        Session["TokenUserTempData"] = cookie["TokenUserTempData"];

                    }
                }
                if (Session["UserName"] != null)
                {
                    int empSeq;
                    Int32.TryParse(Convert.ToString(Session["EmpSeq"]), out empSeq);
                    ltrUserName.Text = emp.GetEmployeeFullName(empSeq);
                    //UpdateUnreadCount();
                    CreatedMenu(Session["UserSeq"].ToString());
                }
            }

            if (Session["EmpSeq"] == null)
            {
                Response.Redirect("Login.aspx");
            }

            GenPopupPrivateEmployeeInfo();

            // For some reason, set cookie here not working when redirect to another module.
            // Resolve by set login session(and cookie) again at masterpage  
            SsMng.SetLoginSession(SsMng.UserSeq, SsMng.EmpSeq, SsMng.UserName, SsMng.WorkingJobSiteSeq, SsMng.PosSeq,
                SsMng.Height, SsMng.TokenKey, SsMng.TokenUserTempData);

            if (SsMng.IsLogin())
            {
                UpdateUnreadCountEdit();
            }
        }

        private void GenPopupPrivateEmployeeInfo()
        {
            //string empSeq = Convert.ToString(Session["EmpSeq"]);
            //string userSeq = Convert.ToString(Session["UserSeq"]);
            //string userName = Convert.ToString(Session["UserName"]);
            //string workingJobSiteSeq = Convert.ToString(Session["WorkingJobSiteSeq"]);
            //string height = Convert.ToString(Session["Height"]);
            //string tokenKey = Convert.ToString(Session["TokenKey"]);
            //string tokenTempData = SsMng.TokenUserTempData;

            ViewState["ParamForPS_EmployeesDtls"] =
                string.Format("?token={0}&redirectPage=./PS_EmployeesDtls.aspx?Sequence={1}",
                    SsMng.TokenUserTempData, SsMng.EmpSeq, false);
        }

        protected void UpdateUnreadCountEdit()
        {
            int nUnwarnCount, nUnreadCount;
            send.GetSendUnwarnUnreadCount(SsMng.EmpSeqI, out nUnwarnCount, out nUnreadCount);

			if (nUnwarnCount > 0)
			{
				lbNotification.Text = string.Format("คุณมีข้อความใหม่ {0}", nUnwarnCount);
				RadToolTip1.Show();
			}

			ltrInboxCount.Text = Convert.ToString(nUnreadCount);
        }

        //protected void UpdateUnreadCount()
        //{ 
        //    int nUnreadCount;// = send.GetUnreadCount(Session["EmpSeq"].ToString());
        //    bool tempUnuse;
        //    messageService.GetSendUnwarnCount(SsMng.EmpSeqI, false, out nUnreadCount, out tempUnuse);
        //    int nOldUnreadCount = Convert.ToInt32(Session["UnreadCount"]);

        //    if (nUnreadCount > nOldUnreadCount)
        //    {
        //        ShowNotification(nUnreadCount);
        //    }

        //    Session["UnreadCount"] = nUnreadCount;
        //    //lblInboxCount.Text = Convert.ToString(nUnreadCount);
        //    ltrInboxCount.Text = Convert.ToString(nUnreadCount);
        //    //imgNew.Visible = nUnreadCount > 0;
        //}

        public void CreatedMenu(string strUserSeq)
        {
            var menuItemList = user.GetMenuItemList("", "ESS");
            foreach (DataRow menuItem in menuItemList.Rows)
            {
                if (menuItem["SEQ"] as int? == 10194)
                {
                    menuItem["TARGET"] = string.Format("{0}?token={1}&redirectPage=./PS_EmployeesDtls.aspx?Sequence={2}",
                            menuItem["TARGET"], SsMng.TokenUserTempData, Session["EmpSeq"]);
                    break;
                }
                if (Convert.ToString(menuItem["PATH"]).ToLower().Contains("ExternalPage.aspx".ToLower()))
                {
                    string t = Convert.ToString(menuItem["PATH"]);
                    //   /ESS/APP_UI/Forms/ExternalPage.aspx?Url=http://@1/WEB.GIMS/Home/SingleSigonCookie?redirectPage=../Prepurchase&isEncode64=false
                    int ind = t.IndexOf("=") + 1;
                    var urlEncoded = System.Web.HttpUtility.UrlEncode(t.Substring(ind));
                    var externalPagePath = "~/APP_UI/Forms/ExternalPage.aspx?Url=";
                    menuItem["PATH"] = externalPagePath + urlEncoded;
                }

                var path = ((menuItem["PATH"] as string) ?? string.Empty);
                if (path.StartsWith(".") && !Request.Url.IsDefaultPort)
                {
                    menuItem["PATH"] = path.Substring(1, path.Length - 1);
                }
            }

            // Interlim แก้ปัญหา 2 เมนู (ใน Server รันได้) ใน Visual รันไม่ได้
            /*
             * 111115	7.2.6	ประเมินตนเอง	111114	~/../GHRMS/APP_UI/Forms/SingleSigon.aspx?redirectPage=./HRDEvaluationRoundCriteria.aspx	NULL	ESS	U	NULL	NULL	NULL	NULL
             * 111116	7.2.7	ผู้บังคับบัญชาประเมิน	111114	~/../GHRMS/APP_UI/Forms/SingleSigon.aspx?redirectPage=./ComponentEvaluate.aspx	NULL	ESS	U	NULL	NULL	NULL	NULL
             */

            foreach (DataRow menuItem in menuItemList.Rows)
            {
                var p = Convert.ToString(menuItem["PATH"]);

                if (Request.Url.ToString().Contains("localhost:"))
                {
                    if (p.StartsWith("~/../"))
                    {
                        menuItem["PATH"] = "#";
                    }
                    continue;
                }

                try
                {
                    Server.MapPath(p);
                }
                catch (Exception ex)
                {
                    if (p.StartsWith("~/../GHRMS/APP_UI"))
                    {
                        string serverName = Request.Url.GetLeftPart(UriPartial.Authority);
                        string prefixName = (ConfigurationSettings.AppSettings["SubSystem"].Length > 0
                            ? "/" + ConfigurationSettings.AppSettings["SubSystem"]
                            : "");
                        menuItem["PATH"] = p.Replace("~/../GHRMS/APP_UI",
                            string.Format("{0}{1}/GHRMS/APP_UI", serverName, prefixName));
                    }
                }
            }

            RadMenu1.DataSource = menuItemList;
            RadMenu1.DataBind();
        }

        protected void cmdLogout_Click(object sender, EventArgs e)
        {
            HttpCookie cookie = Request.Cookies["UserDetail"];

            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddDays(-1);
            }

            RadMenu1.Items.Clear();
            Session.Abandon();
            SsMng.Logout();
            //using (var gs = new GerpAuthenService.GerpAuthenServiceClient())
            //{
            //    //gs.Logout(new Guid(HttpContext.Current.Request.Cookies["UserDetail"]["TokenKey"]), HttpContext.Current.Request.RawUrl);
            //    //gs.DestroyUserTempInfo(cookie["Token"]);
            //} 
            Response.Redirect(@"~\App_UI\Forms\Login.aspx");
        }

        protected void cmdInbox_Click(object sender, EventArgs e)
        {
            Response.Redirect(@"~\App_UI\Forms\TaskLists.aspx");
        }

        protected void cmdSelectSystem_Click(object sender, EventArgs e)
        {
            string hostPart = Request.ServerVariables["HTTP_HOST"];
            string prefixPart = !string.IsNullOrEmpty(ConfigurationSettings.AppSettings["SubSystem"]) &&
                                Request.Url.IsDefaultPort
                ? "/" + ConfigurationSettings.AppSettings["SubSystem"]
                : "";
            string essPart = Request.Url.IsDefaultPort ? "/ESS" : "";
            string httpOrHttps = Request.Url.ToString().ToLower().StartsWith("https") ? "https" : "http";
            //http://192.168.100.14/ESS/App_UI/Forms/SelectSystem.aspx        *** prefixPart = "",         essPart = "/ESS"
            //http://192.168.137.1/KPISERP/ESS/App_UI/Forms/SelectSystem.aspx *** prefixPart = "/KPISERP", essPart = "/ESS"
            //http://localhost:1234/App_UI/Forms/SelectSystem.aspx            *** prefixPart = "",         essPart = "" 
            Response.Redirect(string.Format("{3}://{0}{1}{2}/App_UI/Forms/SelectSystem.aspx", hostPart, prefixPart,
                essPart, httpOrHttps));
        }

        protected void RadMenu1_ItemDataBound(object sender, Telerik.Web.UI.RadMenuEventArgs e)
        {
            string url = e.Item.NavigateUrl;
            if (url.IndexOf("@1") > -1)
            {
                string hostPart = Request.ServerVariables["HTTP_HOST"];
                string prefixPart = !string.IsNullOrEmpty(ConfigurationSettings.AppSettings["SubSystem"]) &&
                                    Request.ServerVariables["SERVER_PORT"] == "80"
                    ? "/" + ConfigurationSettings.AppSettings["SubSystem"]
                    : "";
                e.Item.NavigateUrl = url.Replace("@1", hostPart + prefixPart);
            }
        }
    }
}